<template>
  <div class="app-container">
    <el-card class="box-card" :body-style="{ 'min-height': 'calc(100vh - 110px)',padding: '24px' }">
      <el-row>
        <el-col :span="24">
          <!-- query -->
          <el-form ref="userForm" :inline="true" :model="listQuery">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="listQuery.userName" clearable placeholder="请输入用户名称" />
            </el-form-item>
            <el-form-item label="用户编码" prop="userNo">
              <el-input v-model="listQuery.userNo" clearable placeholder="请输入用户编码" />
            </el-form-item>
            <el-form-item label="登录名称" prop="loginName">
              <el-input v-model="listQuery.loginName" clearable placeholder="请输入登录名称" />
            </el-form-item>
            <!--<el-form-item label="手机号">-->
            <!--<el-input v-model="listQuery.mobile" clearable placeholder="请输入用户手机号" />-->
            <!--</el-form-item>-->
            <!--<el-form-item label="E-mail">-->
            <!--<el-input v-model="listQuery.email" clearable placeholder="请输入用户E-mail" />-->
            <!--</el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
              <el-button @click="resetForm('userForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <!-- <el-button type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button> -->
          <!-- table data -->
          <el-table
            v-loading="listLoading"
            :data="userList"
            border
            header-cell-class-name="table-header-cell"
            style="width: 100%; margin-top:10px;"
          >
            <el-table-column
              prop="sId"
              label="序号"
              type="index"
              width="50px"
              align="center"
            />
            <el-table-column
              v-if="1>2"
              prop="id"
              label="用户ID"
            />
            <el-table-column
              prop="userName"
              label="姓名"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="userNo"
              label="编码"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="loginName"
              label="登录名"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="validateState"
              label="是否有效"
              align="center"
              width="90px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.validateState | validateStateFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="mobile"
              label="手机"
              align="center"
              width="110px"
            />
            <el-table-column
              prop="email"
              label="邮件"
              align="center"
              width="180px"
            />
            <el-table-column
              prop="sex"
              label="性别"
              align="center"
              width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.sex | userSexFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="birthday"
              label="出生日期"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="nationality"
              label="民族"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="education"
              label="学历"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="job"
              label="职务"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="homeAddress"
              label="家庭住址"
              align="center"
              width="300px"
            />
            <el-table-column
              prop="isLocked"
              label="是否锁定"
              align="center"
              width="100px"
            />
            <el-table-column
              prop="loginTime"
              label="最近登录时间"
              align="center"
              width="160px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.loginTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="250" class-name="small-padding fixed-width">
              <template slot-scope="{row}">
                <!-- <el-button type="warning" size="mini" @click="resetPassword(row)">重置密码</el-button> -->
                <el-button type="warning" size="mini" @click="authZTenant(row)">租户授权</el-button>
                <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
                <el-button type="danger" size="mini" @click="handleDelete(row)">删除 </el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />
        </el-col>
      </el-row>
    </el-card>
    <!-- dialog -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="50%">
      <el-form ref="dataForm" :rules="rules" :model="userTemp" label-width="90px" style="width: 80%; margin-left:50px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="userTemp.userName" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户编码" prop="userNo" label-width="100px">
              <el-input v-model="userTemp.userNo" placeholder="请输入用户编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="登录账号" prop="loginName">
              <el-input v-model="userTemp.loginName" placeholder="请输入用户编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex" label-width="100px">
              <!--<el-input v-model="userTemp.sex" placeholder="请输入性别" />-->
              <el-switch v-model="userTemp.sex" style="display: block" active-color="#13ce66" inactive-color="#ff4949" active-text="男" inactive-text="女" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-row :gutter="20">-->
        <!--<el-col :span="12">-->
        <!--<el-form-item label="密码" prop="password">-->
        <!--<el-input v-model="userTemp.password" placeholder="请输入密码" />-->
        <!--</el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--<el-form-item label="再次输入密码" prop="rePassword" label-width="100px">-->
        <!--<el-input v-model="userTemp.rePassword" placeholder="请再次输入密码" />-->
        <!--</el-form-item>-->
        <!--</el-col>-->
        <!--</el-row>-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="userTemp.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="E-mail" prop="email" label-width="100px">
              <el-input v-model="userTemp.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否有效" prop="validateState">
              <el-switch v-model="userTemp.validateState" style="display: block" active-color="#ff4949" inactive-color="#13ce66" active-text="无效" inactive-text="有效" active-value="0" inactive-value="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday" label-width="100px">
              <el-date-picker v-model="userTemp.birthday" type="date" placeholder="出生日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="民族" prop="nationality">
              <el-input v-model="userTemp.nationality" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历" prop="education" label-width="100px">
              <el-input v-model="userTemp.education" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职务" prop="job">
              <el-input v-model="userTemp.job" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭住址" prop="homeAddress" label-width="100px">
              <el-input v-model="userTemp.homeAddress" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="租户授权" :visible.sync="authZTenantDialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-transfer
        v-model="selectTenantIds"
        :data="tenantList"
        :titles="['系统列表', '已选系统']"
        :props="{
          key: 'id',
          label: 'tenantName'
        }"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="authZTenantDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createAuthZTenant">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { fetchUsers, addUser, updateUser, deleteUser, resetPwd } from '@/api/user.js'
import { fetchTenants, getUserTenants } from '@/api/tenant.js'
import { addUserTenant } from '@/api/userTenant.js'

export default {
  name: 'UserManagement',
  components: { Pagination },
  filters: {
    userSexFilter(userSex) {
      switch (userSex) {
        case '0':
          return '女'
        case '1':
          return '男'
      }
    },
    validateStateFilter(state) {
      switch (state) {
        case '0': return '无效'
        case '1': return '有效'
      }
    }
  },
  data() {
    return {
      total: 10,
      listLoading: true,
      userList: null,
      listQuery: {
        current: 1,
        size: 10,
        userName: '',
        userNo: '',
        loginName: '',
        mobile: '',
        email: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      userTemp: {
        userName: '',
        userNo: '',
        loginName: '',
        validateState: 0,
        mobile: '',
        email: '',
        sex: 1,
        birthday: '',
        nationality: '',
        education: '',
        job: '',
        homeAddress: '',
        isLocked: ''

      },
      rules: {
        userName: [{ required: true, message: '用户名称不能为空', trigger: 'change' }],
        userNo: [{ required: true, message: '用户编码不能为空', trigger: 'change' }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'change' }, { validator: validatePhone, trigger: 'change' }],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'change' }, { validator: validateEMail, trigger: 'change' }]
      },
      tenantList: [],
      selectTenantIds: [],
      authZTenantDialogFormVisible: false,
      userId: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    resetRoleTemp() {
      this.userTemp = {
        userName: '',
        userNo: '',
        loginName: '',
        // password: '',
        mobile: '',
        sex: '',
        email: ''
      }
    },
    getList() {
      this.listLoading = true
      fetchUsers(this.listQuery).then(response => {
        const res = response.retBody
        this.userList = res.records
        this.total = res.total
      }).finally(() => {
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    handleUpdate(row) {
      this.userTemp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.resetRoleTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该条用户信息?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除用户成功！',
            type: 'success',
            duration: 1000
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.userTemp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增用户成功',
              type: 'success',
              duration: 1000
            })
            this.getList()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateUser(this.userTemp.id, this.userTemp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改用户信息成功',
              type: 'success',
              duration: 1000
            })
            this.getList()
          })
        }
      })
    },
    resetPassword(row) {
      this.$confirm('确定要重置用户密码吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '密码重置成功',
            type: 'success',
            duration: 1000
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    authZTenant(row) {
      this.userId = row.id
      this.authZTenantDialogFormVisible = true
      this.getTenantList()
    },
    createAuthZTenant() {
      const userTenant = {}
      userTenant.userId = this.userId
      userTenant.tenantIds = this.selectTenantIds
      addUserTenant(userTenant).then(() => {
        this.authZTenantDialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '租户授权成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    getTenantList() {
      const tenantQuery = {
        current: 1,
        size: 500,
        tenantName: '',
        tenantId: ''
      }
      const userTenantQuery = {}
      userTenantQuery.userId = this.userId

      Promise.all([fetchTenants(tenantQuery), getUserTenants(userTenantQuery)]).then(response => {
        const tenantList = response[0].retBody.records
        const userTenantList = response[1].retBody

        this.tenantList = tenantList
        this.selectTenantIds = userTenantList.map(item => {
          return item.id
        })
      })
    }
  }
}

/* 是否手机号码或者固话*/
export function validatePhone(rule, value, callback) {
  const reg = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/
  if (value === '' || value === undefined || value == null) {
    callback()
  } else {
    if ((!reg.test(value)) && value !== '') {
      callback(new Error('请输入正确的电话号码或者固话号码'))
    } else {
      callback()
    }
  }
}
/* 是否邮箱*/
export function validateEMail(rule, value, callback) {
  const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/
  if (value === '' || value === undefined || value == null) {
    callback()
  } else {
    if (!reg.test(value)) {
      callback(new Error('请输入正确的邮箱地址'))
    } else {
      callback()
    }
  }
}
</script>
<style scoped>
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-switch {
    line-height: 27px;
  }
  .fixed-width .el-button--mini {
    width: 68px;
  }
</style>
